#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>
#include <QFile>
#include <QPoint>
#include <QScrollBar>
#include <QLineEdit>
#include <QFontDialog>

#include "textstatusmonitor.h"
#include "imagestatusmonitor.h"
#include "toolutils.h"
#include "svideowidget.h"
#include "sshconsole.h"
#include "audiostatusmonitor.h"
#include "dropmanager.h"

#include <QTimer>
#include <QImage>
#include <QThread>

#include <QSurfaceFormat>
#include <QOpenGLWidget>

// TODO:
// 1. tabs具有scroll的能力 √
// 2. tabs的scroll的一个适应性enabel √
// 采用ScrollArea即可 √

// TODO:
// 1、flatting window √
// 2、音量大小 和 速度的 一个 类dialog √
// 3、视频播放 和 视频界面搭建 √
// 4、将flatting window 封装一下，新建一个 FlattingWindow 类 √
// 5、优化一下toolBars，将没用的去掉，并完善有用的功能

// TODO:
// text --> .txt .* √
// image --> .png .jpg .dmp √
// .mp3 ... 音乐 √
// .mp4 .mov 视频 √
// excel --> .xslx .csv 结合TableView、TableModel、SelectModel来做
// dos/ssh --> √
// word markdown html 富文本编辑

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // setAttribute(Qt::WA_DeleteOnClose);

    DropManager::SetParent(this);
    DropManager::GetInstance()->AddDroppableWidget(ui->droppableWidget);
    // test
    ui->droppableWidget->installEventFilter(DropManager::GetInstance());
    // test#end
    buildUi();
    buildWidgetSignalSlots();
    buildActionSignalSlots();
    // mTimerId = this->startTimer(1000);

    // 创建一个 QOpenGLWidget 并初始化它
    QOpenGLWidget *openGLWidget = new QOpenGLWidget(this);
    openGLWidget->show(); // 强制初始化
    openGLWidget->hide(); // 隐藏
    openGLWidget->deleteLater();
}

MainWindow::~MainWindow()
{
    // this->killTimer(mTimerId);
    DropManager::GetInstance()->RemoveDroppableWidget(ui->droppableWidget);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent* event)
{
    auto focusedWidget = QApplication::focusWidget();
    auto activatedWidget = QApplication::activeWindow();
    if (activatedWidget == nullptr) {
        qDebug() << "MainWindow::timerEvent, activatedWidget == nullptr";
    } else {
        qDebug("MainWindow::timerEvent, activatedWidget is %s", activatedWidget->objectName().toStdString().c_str());
    }

    if (focusedWidget == nullptr) {
        qDebug() << "MainWindow::timerEvent, focusedWidget == nullptr";
    } else {
        qDebug("MainWindow::timerEvent, focusWidget is %s", focusedWidget->objectName().toStdString().c_str());
    }
}


void MainWindow::buildUi()
{
    auto content = new QPlainTextEdit(this);
    content->setObjectName("无标题");
    ui->droppableWidget->AddPageToFocusPagesWidget("无标题", content);

    auto focusPage = ui->droppableWidget->FocusPage();
    if (focusPage.second == nullptr || focusPage.first->ContentType() != DragableTab::TabType::TEXT) {
        return;
    }
    mStatusMonitor = new TextStatusMonitor(qobject_cast<QPlainTextEdit*>(focusPage.second), this);
    ui->statusBar->addWidget(mStatusMonitor, 1);
    ui->statusBar->setStyleSheet("QStatusBar::item { border-right: 0.5px solid rgb(50, 50, 50); }"); // 改变分隔符颜色
    ui->statusBar->setStyleSheet("QStatusBar::item { border: none; }"); // 去掉分割符
    ui->statusBar->setMinimumHeight(30);    // 调整最小高度，组件太小影响status的高度
}

// TODO:
// 这个地方需要大改，在相关组件show时connect，在组件hide时disconnect
// connect 和 disconnect 分别对应了 page、status、menu，toolBar
void MainWindow::buildWidgetSignalSlots()
{
    connect(ui->droppableWidget, &DroppableWidget::FocusPageChanged, this, &MainWindow::OnFocusPageChangedSlots);
    connect(ui->droppableWidget, &DroppableWidget::AllPagesClosed, this, &MainWindow::close);
}

// 完成OK，实现了删除焦点page，CTRL+W
void MainWindow::onClickActionClosePageSlots()
{
    qDebug("removeFocusPage");
    ui->droppableWidget->RemoveFocusPage();
}

// 这个地方需要大改，在相关组件show时connect，在组件hide时disconnect √
void MainWindow::buildActionSignalSlots()
{
    connect(ui->actionCreateFile, &QAction::triggered, this, &MainWindow::onClickActionCreateSlot);
    connect(ui->actionOpenFile, &QAction::triggered, this, &MainWindow::onClickActionOpenSlot);
    connect(ui->actionCreateNewSsh, &QAction::triggered, this, &MainWindow::onClickACtionCreateNewSsh);
    connect(ui->actionSaveFile, &QAction::triggered, this, &MainWindow::onClickActionSaveSlot);
    connect(ui->actionSaveAsFile, &QAction::triggered, this, &MainWindow::onClickActionSaveAsSlot);
    connect(ui->actionExitProcess, &QAction::triggered, this, [this] () { this->close(); });
    connect(ui->actionClosePage, &QAction::triggered, this, &MainWindow::onClickActionClosePageSlots);

    // 考虑移除这几个东西，粗体斜体这些貌似不需要现在，字体倒是可以先保留到
    // 可以考虑增加一个zoom，方便放大和减小字体
    connect(ui->actionSetFont, &QAction::triggered, this, &MainWindow::onClickActionSetFont);
    connect(ui->actionBoldText, &QAction::triggered, this, &MainWindow::onClickActionBoldSlot);
    connect(ui->actionItalicText, &QAction::triggered, this, &MainWindow::onClickActionItalicSlot);
    connect(ui->actionUnderlineText, &QAction::triggered, this, &MainWindow::onClickActionUnderlineSlot);

}

void MainWindow::BuildTextPageActionSignalSlots(QWidget* content, DragableTab::TabType type)
{
    if (type == DragableTab::TabType::TEXT) {
        auto textEdit = qobject_cast<QPlainTextEdit*>(content);
        connect(ui->actionCutText, &QAction::triggered, textEdit, &QPlainTextEdit::cut);
        connect(ui->actionCopyText, &QAction::triggered, textEdit, &QPlainTextEdit::copy);
        connect(ui->actionPasteText, &QAction::triggered, textEdit, &QPlainTextEdit::paste);
        connect(ui->actionUndoText, &QAction::triggered, textEdit, &QPlainTextEdit::undo);
        connect(ui->actionRedoText, &QAction::triggered, textEdit, &QPlainTextEdit::redo);
        connect(ui->actionSelectAllText, &QAction::triggered, textEdit, &QPlainTextEdit::selectAll);
    }
}

void MainWindow::OnFocusPageChangedSlots()
{
    if (mStatusMonitor != nullptr) {
        mStatusMonitor->close();
        ui->statusBar->removeWidget(mStatusMonitor);
        delete mStatusMonitor;
        mStatusMonitor = nullptr;
    }

    auto focusPage = ui->droppableWidget->FocusPage();
    if (focusPage.first->ContentType() == DragableTab::TabType::TEXT){
        mStatusMonitor = new TextStatusMonitor(qobject_cast<QPlainTextEdit*>(focusPage.second), this);
        ui->statusBar->addWidget(mStatusMonitor, 1);
    }

    if (focusPage.first->ContentType() == DragableTab::TabType::IMAGE){
        mStatusMonitor = new ImageStatusMonitor(qobject_cast<ImageEditor*>(focusPage.second), this);
        ui->statusBar->addWidget(mStatusMonitor, 1);
    }

    if (focusPage.first->ContentType() == DragableTab::TabType::MUSIC) {
        mStatusMonitor = new audioStatusMonitor(qobject_cast<SVideoWidget*>(focusPage.second), this);
        ui->statusBar->addWidget(mStatusMonitor, 1);
    }

    BuildTextPageActionSignalSlots(focusPage.second, focusPage.first->ContentType());
}

// 完成OK，实现了创建新标签页的功能
void MainWindow::onClickActionCreateSlot()
{
    std::string s = "无标题" + std::to_string(counts++);
    ui->droppableWidget->AddPageToFocusPagesWidget(QString::fromStdString(s), new QPlainTextEdit(this), DragableTab::TabType::TEXT);
}

// 待拓展，增加不同类型的文件类型加载
void MainWindow::onClickActionOpenSlot()
{
    auto [tab, content] = ToolUtils::OpenPage(this);
    ui->droppableWidget->AddPageToFocusPagesWidget(tab, content);
}

void MainWindow::onClickACtionCreateNewSsh()
{
    if (mSshCreateGuide == nullptr) {
        mSshCreateGuide = new SshCreateGuide(this);
        connect(mSshCreateGuide, &SshCreateGuide::RequestCreateSshConsole, this, [this](SshConsole* sshConsole) {
            auto title = "ssh(172.22.78.205)";
            ui->droppableWidget->AddPageToFocusPagesWidget(title, sshConsole, DragableTab::TabType::SSH);
        });
    }
    mSshCreateGuide->exec();
}

// 完成OK，后续拓展可以放到toolUtils里面搞
void MainWindow::onClickActionSaveSlot()
{
    ToolUtils::SavePage(ui->droppableWidget->FocusPage(), this);
}

// 完成OK，后续拓展可以放到toolUtils里面搞
void MainWindow::onClickActionSaveAsSlot()
{
    ToolUtils::SavePageAs(ui->droppableWidget->FocusPage(), this);
}

// 待定，考虑是否留下
void MainWindow::onClickActionSetFont()
{
    bool ok = false;
    // auto newFont = QFontDialog::getFont(&ok, ui->textEdit->currentFont(), this, "设置选择字段字体");
    // ui->textEdit->setCurrentFont(newFont);
}

// 待定，考虑是否留下
void MainWindow::onClickActionBoldSlot(bool checked)
{
    // auto fmt = ui->textEdit->currentCharFormat();
    // fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
    // ui->textEdit->mergeCurrentCharFormat(fmt);
}

// 待定，考虑是否留下
void MainWindow::onClickActionItalicSlot(bool checked)
{
    // auto fmt = ui->textEdit->currentCharFormat();
    // fmt.setFontItalic(checked);
    // ui->textEdit->mergeCurrentCharFormat(fmt);
}

// 待定，考虑是否留下
void MainWindow::onClickActionUnderlineSlot(bool checked)
{
    // auto fmt = ui->textEdit->currentCharFormat();
    // fmt.setFontUnderline(checked);
    // ui->textEdit->mergeCurrentCharFormat(fmt);
}
